package ex20.standardmbeantest;

import javax.management.*;

/**
 * @packgeName: ex20
 * @ClassName: StandardAgent
 * @copyright: CopyLeft
 * @description:<描述>
 * @author: lili
 * @date: 2017/9/1-23:24
 * @version: 1.0
 * @since: JDK 1.8
 */
public class StandardAgent {

    private MBeanServer mBeanServer = null;

    public StandardAgent() {
        mBeanServer = MBeanServerFactory.createMBeanServer();
    }

    public MBeanServer getMBeanServer() {
        return mBeanServer;
    }

    public ObjectName createObjectName(String name){
        ObjectName objectName = null;

        try {
            objectName = new ObjectName(name);
        } catch (Exception e) {
            //忽略异常
        }

        return objectName;
    }

    private void createStandardBean(ObjectName objectName, String managedResourceClassName){

        try {
            mBeanServer.createMBean(managedResourceClassName,objectName);
        } catch (Exception e) {

        }
    }

    public static void main(String[] args) throws InterruptedException {
        StandardAgent agent = new StandardAgent();
        MBeanServer mBeanServer = agent.getMBeanServer();
        String domain = mBeanServer.getDefaultDomain();
        String managedResourceClassName = StandardAgent.class.getPackage().getName() + ".Car";
        ObjectName objectName = agent.createObjectName(domain+":type="+managedResourceClassName);
        agent.createStandardBean(objectName, managedResourceClassName);

        try {
            Attribute colorAttribute = new Attribute("Color","blue");
            mBeanServer.setAttribute(objectName, colorAttribute);
            System.out.println(mBeanServer.getAttribute(objectName, "Color"));
            mBeanServer.invoke(objectName,"drive",null,null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
